import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/customWidget/addRoomTextField.dart';
import 'package:landlore/model/roomInfo.dart';

import '../dbUtil/databaseHelper.dart';

class RoomEditScreen extends StatefulWidget {
  final RoomInfo roomInfo;

  RoomEditScreen({super.key, required this.roomInfo});

  @override
  State<RoomEditScreen> createState() => _RoomEditScreenState();
}

class _RoomEditScreenState extends State<RoomEditScreen> {
  RoomInfo? roomInfo;
  TextEditingController c1 = TextEditingController();
  TextEditingController c2 = TextEditingController();
  TextEditingController c3 = TextEditingController();
  TextEditingController c4 = TextEditingController();
  TextEditingController c5 = TextEditingController();
  TextEditingController c6 = TextEditingController();
  TextEditingController cTemp1 = TextEditingController();
  TextEditingController cTemp2 = TextEditingController();
  TextEditingController cTemp3 = TextEditingController();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    roomInfo = widget.roomInfo == null ? RoomInfo.empty() : widget.roomInfo;
  }

  @override
  void dispose() {
    c1.dispose();
    c2.dispose();
    c3.dispose();
    c4.dispose();
    c5.dispose();
    c6.dispose();
    cTemp1.dispose();
    cTemp2.dispose();
    cTemp3.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      ///设置文字大小不随系统设置改变
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color(0xffe9c46a),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 35.sp,
              color: Colors.black,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            "编辑",
            style: TextStyle(
                decoration: TextDecoration.none,
                fontSize: 35.sp,
                color: Colors.black,
                fontWeight: FontWeight.w900),
          ),
          // actions: [
          //   IconButton(
          //     icon: Icon(
          //       Icons.check_outlined,
          //       size: 35.sp,
          //       color: Colors.black,
          //     ),
          //     onPressed: () async {
          //       //检测数据
          //       List fieldNames = [
          //         '房号',
          //         // '地址',
          //         // '联系人'
          //         // ,'电话'
          //         '租金',
          //         '附加费',
          //         '电费',
          //         '水费'
          //       ];
          //       List<TextEditingController> controllers = [
          //         c1,
          //         c2,
          //         c3,
          //         c4,
          //         c5,
          //       ];
          //
          //       for (int i = 0; i < controllers.length; i++) {
          //         //检测输入内容不能为空
          //         if (controllers[i].text.isEmpty) {
          //           // Show a snackbar or an alert dialog to notify which field is empty
          //           final snackBar = SnackBar(
          //             content: Text(
          //               '${fieldNames[i]} 不能为空!',
          //               style:
          //               TextStyle(fontSize: 20.sp, color: Colors.redAccent),
          //             ),
          //           );
          //           ScaffoldMessenger.of(context).showSnackBar(snackBar);
          //           return;
          //         }
          //         //检测房屋代号是否已存在
          //         if (i == 0) {
          //           bool roomNumExist = await DatabaseHelper.instance
          //               .checkRoomNumExist(controllers[0].text,roomInfo?.id);
          //           if (roomNumExist) {
          //             final snackBar = SnackBar(
          //               content: Text(
          //                 '房屋代号已存在!请输入其他代号',
          //                 style: TextStyle(
          //                     fontSize: 20.sp, color: Colors.redAccent),
          //               ),
          //             );
          //             ScaffoldMessenger.of(context).showSnackBar(snackBar);
          //             return;
          //           }
          //         }
          //       }
          //       //DB保存数据
          //       print(roomInfo);
          //       DatabaseHelper dbHelper = DatabaseHelper.instance;
          //       if (roomInfo?.id == null) {
          //         dbHelper.insertData(roomInfo!.toMap(), TableName.ROOM_INFO);
          //       } else {
          //         dbHelper.updateData(roomInfo!.toMap(), TableName.ROOM_INFO,
          //             primaryKey: 'id', primaryKeyValue: roomInfo!.id!);
          //       }
          //
          //       Navigator.pop(context);
          //     },
          //   )
          // ],
          centerTitle: true,
        ),
        body: Container(
          decoration:  BoxDecoration(
              color: const Color(0xfff4a261),
              image: DecorationImage(
                  image: const AssetImage('assets/images/crossword.png'),
                  repeat: ImageRepeat.repeat,
                  colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.3), BlendMode.srcIn)
              )),
          child: SingleChildScrollView(
            child: Column(
              children: [
                AddRoomTextField(
                  title: "房屋代号",
                  value: roomInfo?.roomNum,
                  controller: c1,
                  digitsOnly: false,
                  callback: (value) {
                    roomInfo?.roomNum = value;
                  },
                ),
                AddRoomTextField(
                    title: "地址(选填)",
                    value: roomInfo?.address,
                    //电话可以为空
                    controller: cTemp1,
                    digitsOnly: false,
                    callback: (value) {
                      value ?? '';
                      roomInfo?.address = value;
                    }),
                AddRoomTextField(
                    title: "联系人(选填)",
                    value: roomInfo?.contact,
                    controller: cTemp2,
                    digitsOnly: false,
                    callback: (value) {
                      value ?? '';
                      roomInfo?.contact = value;
                    }),
                AddRoomTextField(
                    title: "电话(选填)",
                    value: roomInfo?.phone,
                    //电话可以为空
                    controller: cTemp3,
                    digitsOnly: true,
                    callback: (value) {
                      value ?? '';
                      roomInfo?.phone = value;
                    }),
                AddRoomTextField(
                    title: "租金",
                    unit: "元",
                    value: roomInfo?.rent != null
                        ? roomInfo?.rent!.toStringAsFixed(0)
                        : null,
                    controller: c2,
                    digitsOnly: true,
                    callback: (value) {
                      roomInfo?.rent = double.tryParse(value) ?? 0.0;
                    }),
                AddRoomTextField(
                    title: "附加费",
                    unit: "元",
                    controller: c3,
                    digitsOnly: true,
                    value: roomInfo?.otherCharge != null
                        ? roomInfo?.otherCharge!.toStringAsFixed(1)
                        : null,
                    callback: (value) {
                      roomInfo?.otherCharge = double.tryParse(value) ?? 0.0;
                    }),
                AddRoomTextField(
                    title: "电费标准",
                    unit: "元/度",
                    controller: c4,
                    digitsOnly: true,
                    value: roomInfo?.electricityCharge != null
                        ? roomInfo?.electricityCharge!.toStringAsFixed(1)
                        : null,
                    callback: (value) {
                      roomInfo?.electricityCharge =
                          double.tryParse(value) ?? 0.0;
                    }),
                AddRoomTextField(
                  title: "水费标准",
                  unit: "元/吨",
                  controller: c5,
                  digitsOnly: true,
                  value: roomInfo?.waterCharge != null
                      ? roomInfo?.waterCharge!.toStringAsFixed(1)
                      : null,
                  callback: (value) {
                    roomInfo?.waterCharge = double.tryParse(value) ?? 0.0;
                  },
                ),
                Container(
                    padding: EdgeInsets.only(left: 100.w, right: 100.w),
                    margin: EdgeInsets.only(top: 40.h, bottom: 0.h),
                    height: 60.h,
                    child: ElevatedButton(
                        onPressed: () async {
                          //检测数据
                          List fieldNames = [
                            '房号',
                            // '地址',
                            // '联系人'
                            // ,'电话'
                            '租金',
                            '附加费',
                            '电费',
                            '水费'
                          ];
                          List<TextEditingController> controllers = [
                            c1,
                            c2,
                            c3,
                            c4,
                            c5,
                          ];

                          for (int i = 0; i < controllers.length; i++) {
                            //检测输入内容不能为空
                            if (controllers[i].text.isEmpty) {
                              // Show a snackbar or an alert dialog to notify which field is empty
                              final snackBar = SnackBar(
                                content: Text(
                                  '${fieldNames[i]} 不能为空!',
                                  style:
                                  TextStyle(fontSize: 20.sp, color: Colors.redAccent),
                                ),
                              );
                              ScaffoldMessenger.of(context).showSnackBar(snackBar);
                              return;
                            }
                            //检测房屋代号是否已存在
                            if (i == 0) {
                              bool roomNumExist = await DatabaseHelper.instance
                                  .checkRoomNumExist(controllers[0].text,roomInfo?.id);
                              if (roomNumExist) {
                                final snackBar = SnackBar(
                                  content: Text(
                                    '房屋代号已存在!请输入其他代号',
                                    style: TextStyle(
                                        fontSize: 20.sp, color: Colors.redAccent),
                                  ),
                                );
                                ScaffoldMessenger.of(context).showSnackBar(snackBar);
                                return;
                              }
                            }
                          }
                          //DB保存数据
                          print(roomInfo);
                          DatabaseHelper dbHelper = DatabaseHelper.instance;
                          if (roomInfo?.id == null) {
                            dbHelper.insertData(roomInfo!.toMap(), TableName.ROOM_INFO);
                          } else {
                            dbHelper.updateData(roomInfo!.toMap(), TableName.ROOM_INFO,
                                primaryKey: 'id', primaryKeyValue: roomInfo!.id!);
                          }

                          Navigator.pop(context);
                        },
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(
                                Colors.blue)),
                        child: Text(
                          '提交',
                          style: TextStyle(
                              fontSize: 35.sp, fontWeight: FontWeight.w600),
                        ))),
                SizedBox(
                  height: 200.h,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
